import { Component,Input,OnInit,SimpleChanges, OnChanges, EventEmitter, Output, ViewChild, ElementRef } from '@angular/core';
import { ElTableSlotEvent, TableColumnDataItem } from '../table.interface';
import { ElTableFormat } from '../utils/format';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'el-table-body',
  templateUrl: './table-body.component.html',
})
export class TableBodyComponent implements OnInit,OnChanges {
  tableFormat: ElTableFormat = new ElTableFormat;
  private sanitizer:any;
  @Input() model: any = [];
  @Input() stripe: boolean = false;
  @Input() center: boolean = false;
  @Input() layout: any;
  @Input() rowClassName!: (userRow: any, index: number) => string;
  @Output() cellClick: EventEmitter<ElTableSlotEvent>=new EventEmitter();
  @Output() cellDblClick: EventEmitter<ElTableSlotEvent>=new EventEmitter();
  @Output() cellMouseEnter: EventEmitter<Event>=new EventEmitter();
  @Output() cellMouseLeave: EventEmitter<Event>=new EventEmitter();
  @Output() formatModel: any[] = [];
  constructor(tableFormat: ElTableFormat, sanitizer: DomSanitizer){
    this.tableFormat = tableFormat;
        this.sanitizer = sanitizer;
  };

  ngOnChanges(changes: SimpleChanges): void {
     // not include model
     if (!changes || !changes.model)
     return;
 this.formatModel = this.tableFormat.formatRowData(this.model);
  }

  ngOnInit(): void {
    
  }

  renderHtml(str:string) {
    return this.sanitizer.bypassSecurityTrustHtml(str);
  }

  merge(domHandle:any, next:any){
    return Object.assign(domHandle, next);
  }

  isTemplateRef(content:any) {
    return content && typeof content === 'object';
  }

  getBodyWidth(){
    var /** @type {?} */ width = ElTableFormat.getCSSValue(this.layout.bodyWidth);
        if (!width)
            return this.layout.bodyWidth;
        return width - this.layout.scrollBarWidth;
  }

  getFormatModel(index:number){
    return this.formatModel[index];
  }

  destroyRowFunc(index:number){
    var _this = this;
    return function () {
        _this.model.splice(index, 1);
        _this.formatModel = _this.tableFormat.formatRowData(_this.model);
    };
  }

  makeRowClass(index:number){
    var /** @type {?} */ userRows = this.formatModel[index];
    var /** @type {?} */ userClass = this.rowClassName ? this.rowClassName(userRows, index) : '';
    return 'el-table__row ' + userClass;
  }

  doubleClickHandle(event:any, Ref:any){
    Ref.event = event;
        this.cellDblClick.emit(Ref);
  }

  clickHandle(event:any, Ref:any){
    Ref.event = event;
        this.cellClick.emit(Ref);
  }

  cellMouseActionHandle(event:any, isEnter:any){
    if (isEnter)
            return this.cellMouseEnter.emit(event);
        this.cellMouseLeave.emit(event);
  }
}
